import { useMockData } from '@/config/env';
import * as mock from '@/mock/bom';
import { Materials } from '@/types/orderInfo';
import { materials2OrderInfo } from '@/utils';
import { useRequest } from 'ahooks';
import { message } from 'antd';
import { isEmpty } from 'lodash-es';

export default function orderInfo() {
  const orderResult = useRequest(
    async () => {
      if (useMockData) {
        return materials2OrderInfo(
          mock.materials as unknown as Materials,
          mock.orderIds,
        );
      }
      let orderIds = [];
      // (await Manycore.Miniapp.uploadDataAsync({ miniappId: 'bom-sync', data: JSON.stringify({ orderIds: ['3FO4K4WPMP95'] }) })).uniqueId; // GyBZoIKHBdf2kukmkJ70yCYqmEQLqm95
      try {
        const data = JSON.parse(await Manycore.Miniapp.getUploadedDataAsync());
        orderIds = data?.orderIds ?? [data.orderId];
        // console.log(orderIds);
      } catch (error) {
        if (isEmpty(orderIds)) {
          throw new Error('获取orderIds失败');
        }
      }
      const materials = await Manycore.Integration.Bom.findMaterialsAsync({
        orderIds,
      });
      const orderInfos = materials2OrderInfo(materials, orderIds);
      // console.log({ materials, orderInfos });
      return orderInfos;
    },
    {
      onError: (error) => {
        console.error(error);
        message.error(`获取订单数据失败: ${error.message}`);
      },
    },
  );
  return { orderResult };
}
